<template>
  <div class="page-container router-view-container">
    <!-- 页面头部 -->
    <PageHeader title="房屋成本明细管理" :subtitle="`总数: ${pagination.total}`">
      <!-- 搜索和筛选区域 -->
      <template #search-filters>
        <div class="cost-detail-search">
          <span class="label">门牌地址：</span>
          <el-input
            v-model="searchParams.mpdz"
            placeholder="请输入门牌地址搜索"
            style="width: 300px"
            clearable
            @input="handleSearch"
          >
            <template #prefix>
              <el-icon><Location /></el-icon>
            </template>
          </el-input>
        </div>
        
        <div class="cost-detail-room-search">
          <span class="label">房号：</span>
          <el-input
            v-model="searchParams.fh"
            placeholder="请输入房号搜索"
            style="width: 200px"
            clearable
            @input="handleSearch"
          >
            <template #prefix>
              <el-icon><House /></el-icon>
            </template>
          </el-input>
        </div>
        
        <div class="cost-detail-function-select">
          <span class="label">房屋功能：</span>
          <el-select
            v-model="searchParams.fwgn"
            placeholder="房屋功能"
            clearable
            style="width: 150px"
            @change="handleFilterChange"
          >
            <el-option label="全部" value="" />
            <el-option label="办公" value="办公" />
            <el-option label="住宅" value="住宅" />
            <el-option label="商业" value="商业" />
            <el-option label="车位" value="车位" />
            <el-option label="其他" value="其他" />
          </el-select>
        </div>
        
        <div class="cost-detail-status-select">
          <span class="label">状态：</span>
          <el-select
            v-model="searchParams.zt"
            placeholder="状态"
            clearable
            style="width: 150px"
            @change="handleFilterChange"
          >
            <el-option label="全部" value="" />
            <el-option label="活动" :value="1" />
            <el-option label="无效" :value="0" />
            <el-option label="历史" :value="2" />
          </el-select>
        </div>
      </template>

      <!-- 主要操作按钮 -->
      <template #main-actions>
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          新增明细
        </el-button>
        
        <el-button type="success" @click="handleBatchAdd">
          <el-icon><DocumentAdd /></el-icon>
          批量录入
        </el-button>
        
        <el-button type="warning" @click="handleExport">
          <el-icon><Download /></el-icon>
          导出Excel
        </el-button>
        
        <el-button type="info" @click="handleImport">
          <el-icon><Upload /></el-icon>
          导入Excel
        </el-button>
      </template>

      <!-- 更多操作下拉菜单 -->
      <template #more-actions>
        <!-- 空内容 -->
      </template>
    </PageHeader>

    <!-- 数据表格 -->
    <div class="table-container">
      <BaseTable
        table-name="cost-detail-table"
        :columns="tableColumns"
        :data="tableData"
        :loading="loading"
        :sort="sort"
        @sort-change="handleSortChange"
      >
        <!-- 门牌地址 -->
        <template #mpdz="{ row }">
          <span class="address-text">{{ row.mpdz }}</span>
        </template>
        
        <!-- 房号 -->
        <template #fh="{ row }">
          <span class="room-text">{{ row.fh }}</span>
        </template>
        
        <!-- 房屋功能 -->
        <template #fwgn="{ row }">
          <el-tag
            :type="getFunctionTagType(row.fwgn)"
            size="small"
          >
            {{ row.fwgn }}
          </el-tag>
        </template>
        
        <!-- 建筑面积 -->
        <template #jzmj="{ row }">
          <span class="area-text">{{ formatNumber(row.jzmj) }} m²</span>
        </template>
        
        <!-- 单方成本 -->
        <template #dfcb="{ row }">
          <span class="cost-text">{{ formatCurrency(row.dfcb) }}</span>
        </template>
        
        <!-- 总成本 -->
        <template #zcb="{ row }">
          <span class="total-cost-text">{{ formatCurrency(row.zcb) }}</span>
        </template>
        
        <!-- 状态 -->
        <template #zt="{ row }">
          <el-tag
            :type="getStatusTagType(row.zt)"
            size="small"
          >
            {{ getStatusText(row.zt) }}
          </el-tag>
        </template>
        
        <!-- 版本 -->
        <template #bb="{ row }">
          <span class="version-text">{{ row.bb }}</span>
        </template>
        
        <!-- 操作 -->
        <template #actions="{ row }">
          <div class="action-buttons">
            <el-button
              type="primary"
              size="small"
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </div>
        </template>
      </BaseTable>
    </div>
    
    <!-- 分页 -->
    <div class="pagination-wrapper">
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.size"
        :total="pagination.total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600px" class="management-dialog">
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="120px" class="dialog-form">
        <el-form-item label="房源成本ID" prop="fycbId">
          <el-input v-model="formData.fycbId" disabled />
        </el-form-item>
        <el-form-item label="房源选择" prop="fyId">
          <el-select v-model="formData.fyId" placeholder="请选择房源" style="width: 100%" @change="handleHouseChange">
            <el-option v-for="house in houseOptions" :key="house.id" :label="`${house.mpdz} - ${house.fh} (${house.fwgn})`" :value="house.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="建筑面积" prop="jzmj">
          <el-input v-model="formData.jzmj" disabled>
            <template #append>m²</template>
          </el-input>
        </el-form-item>
        <el-form-item label="单方成本" prop="dfcb">
          <el-input-number v-model="formData.dfcb" :precision="2" :min="0" style="width: 100%" @change="calculateTotalCost" />
        </el-form-item>
        <el-form-item label="总成本" prop="zcb">
          <el-input-number v-model="formData.zcb" :precision="2" :min="0" style="width: 100%" disabled />
        </el-form-item>
        <el-form-item label="状态" prop="zt">
          <el-select v-model="formData.zt" style="width: 100%">
            <el-option label="活动" :value="1" />
            <el-option label="无效" :value="0" />
            <el-option label="历史" :value="2" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 批量录入对话框 -->
    <el-dialog v-model="batchDialogVisible" title="批量录入" width="800px" class="management-dialog">
      <el-form ref="batchFormRef" :model="batchFormData" :rules="batchFormRules" label-width="120px" class="dialog-form">
        <el-form-item label="房屋功能" prop="fwgn">
          <el-select v-model="batchFormData.fwgn" placeholder="请选择房屋功能" style="width: 100%" @change="handleBatchHouseChange">
            <el-option label="办公" value="办公" />
            <el-option label="住宅" value="住宅" />
            <el-option label="商业" value="商业" />
            <el-option label="车位" value="车位" />
            <el-option label="其他" value="其他" />
          </el-select>
        </el-form-item>
        
        <!-- 房源统计信息 -->
        <el-form-item label="房源统计">
          <div v-if="batchHouses.length > 0" class="house-stats">
            <el-row :gutter="20">
              <el-col :span="8">
                <div class="stat-item">
                  <div class="stat-label">房源套数</div>
                  <div class="stat-value">{{ batchHouses.length }} 套</div>
                </div>
              </el-col>
              <el-col :span="8">
                <div class="stat-item">
                  <div class="stat-label">建筑面积合计</div>
                  <div class="stat-value">{{ formatNumber(batchTotalArea) }} m²</div>
                </div>
              </el-col>
              <el-col :span="8">
                <div class="stat-item">
                  <div class="stat-label">平均面积</div>
                  <div class="stat-value">{{ formatNumber(batchAvgArea) }} m²</div>
                </div>
              </el-col>
            </el-row>
          </div>
          <div v-else class="no-houses">请先选择房屋功能</div>
        </el-form-item>
        
        <!-- 房源列表 -->
        <el-form-item label="房源列表">
          <div v-if="batchHouses.length > 0" class="batch-houses">
            <div v-for="house in batchHouses" :key="house.id" class="house-item">
              <span>{{ house.mpdz }} - {{ house.fh }}</span>
              <span>建筑面积: {{ formatNumber(house.jzmj) }} m²</span>
            </div>
          </div>
          <div v-else class="no-houses">请先选择房屋功能</div>
        </el-form-item>
        
        <el-form-item label="总成本" prop="totalCost">
          <el-input-number v-model="batchFormData.totalCost" :precision="2" :min="0" style="width: 100%" @change="calculateBatchCosts" />
        </el-form-item>
        <el-form-item label="单方成本">
          <el-input v-model="batchFormData.dfcb" disabled>
            <template #append>元/m²</template>
          </el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="batchDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleBatchSubmit">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 导入对话框 -->
    <el-dialog v-model="importDialogVisible" title="导入Excel" width="500px" class="management-dialog">
      <el-upload ref="uploadRef" :action="''" :auto-upload="false" :on-change="handleFileChange" :before-upload="beforeUpload" accept=".xlsx,.xls" drag>
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip">只能上传 xlsx/xls 文件，且不超过 10MB</div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="importDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleImportSubmit">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, DocumentAdd, Download, Upload, Location, House, Search, Refresh, UploadFilled } from '@element-plus/icons-vue'
import BaseTable from '@/components/tools/BaseTable.vue'
import { costDetailApi } from '@/api/costDetailApi.js'
import { houseApi } from '@/api/houseApi.js'
import { formatCurrency, formatNumber } from '@/utils/formatter.js'
import PageHeader from '@/components/layout/PageHeader.vue'

// 路由
const route = useRoute()

// 获取路由参数
const fycbId = computed(() => route.params.fycbId)

// 批量录入统计信息
const batchTotalArea = computed(() => {
  return batchHouses.value.reduce((sum, house) => sum + (house.jzmj || 0), 0)
})

const batchAvgArea = computed(() => {
  if (batchHouses.value.length === 0) return 0
  return batchTotalArea.value / batchHouses.value.length
})

// 表格数据
const tableData = ref([])
const loading = ref(false)

// 排序
const sort = ref({})

// 表格列配置
const tableColumns = [
  { prop: 'mpdz', label: '门牌地址', minWidth: 200, slot: 'mpdz', visible: true },
  { prop: 'fh', label: '房号', width: 120, slot: 'fh', visible: true },
  { prop: 'fwgn', label: '房屋功能', width: 120, slot: 'fwgn', visible: true },
  { prop: 'jzmj', label: '建筑面积', width: 140, slot: 'jzmj', visible: true },
  { prop: 'dfcb', label: '单方成本', width: 140, slot: 'dfcb', visible: true },
  { prop: 'zcb', label: '总成本', width: 140, slot: 'zcb', visible: true },
  { prop: 'zt', label: '状态', width: 100, slot: 'zt', visible: true },
  { prop: 'bb', label: '版本', width: 100, slot: 'bb', visible: true },
  { prop: 'actions', label: '操作', width: 150, slot: 'actions', fixed: 'right', visible: true }
]

// 搜索参数
const searchParams = reactive({
  mpdz: '',
  fh: '',
  fwgn: '',
  zt: ''
})

// 分页
const pagination = reactive({
  page: 1,
  size: 20,
  total: 0
})

// 对话框状态
const dialogVisible = ref(false)
const batchDialogVisible = ref(false)
const importDialogVisible = ref(false)
const dialogTitle = ref('新增明细')

// 表单数据
const formRef = ref()
const formData = reactive({
  id: null,
  fycbId: '',
  fyId: null,
  dfcb: 0,
  zcb: 0,
  zt: 1,
  jzmj: 0
})

// 批量录入表单数据
const batchFormRef = ref()
const batchFormData = reactive({
  fwgn: '',
  totalCost: 0,
  dfcb: 0
})

// 房源选项
const houseOptions = ref([])
const batchHouses = ref([])

// 文件上传
const uploadRef = ref()
const selectedFile = ref(null)

// 表单验证规则
const formRules = {
  fycbId: [{ required: true, message: '房源成本ID不能为空', trigger: 'blur' }],
  fyId: [{ required: true, message: '请选择房源', trigger: 'change' }],
  dfcb: [{ required: true, message: '单方成本不能为空', trigger: 'blur' }],
  zt: [{ required: true, message: '请选择状态', trigger: 'change' }]
}

const batchFormRules = {
  fwgn: [{ required: true, message: '请选择房屋功能', trigger: 'change' }],
  totalCost: [{ required: true, message: '总成本不能为空', trigger: 'blur' }]
}

// 监听fycbId变化
watch(fycbId, (newVal) => {
  if (newVal) {
    formData.fycbId = newVal
    loadData()
  }
})

// 加载数据
const loadData = async () => {
  if (!fycbId.value) return
  
  loading.value = true
  try {
    const params = {
      page: pagination.page,
      size: pagination.size,
      fycbId: fycbId.value,
      ...searchParams,
      sort: sort.value
    }
    
    const response = await costDetailApi.getCostDetailsJoin(params)
    tableData.value = response.data || []
    pagination.total = response.total || 0
  } catch (error) {
    console.error('加载数据失败:', error)
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

// 搜索处理
const handleSearch = () => {
  pagination.page = 1
  loadData()
}

// 筛选变化处理
const handleFilterChange = () => {
  handleSearch()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchParams, {
    mpdz: '',
    fh: '',
    fwgn: '',
    zt: ''
  })
  handleSearch()
}

// 分页处理
const handleSizeChange = (size) => {
  pagination.size = size
  pagination.page = 1
  loadData()
}

const handleCurrentChange = (page) => {
  pagination.page = page
  loadData()
}

// 排序处理
const handleSortChange = (sortInfo) => {
  sort.value = sortInfo
  loadData()
}

// 新增处理
const handleAdd = () => {
  dialogTitle.value = '新增明细'
  Object.assign(formData, {
    id: null,
    fycbId: fycbId.value,
    fyId: null,
    dfcb: 0,
    zcb: 0,
    zt: 1,
    jzmj: 0
  })
  loadHouseOptions()
  dialogVisible.value = true
}

// 编辑处理
const handleEdit = (row) => {
  dialogTitle.value = '编辑明细'
  Object.assign(formData, {
    id: row.id,
    fycbId: row.fycbId,
    fyId: row.fyId,
    dfcb: row.dfcb,
    zcb: row.zcb,
    zt: row.zt,
    jzmj: row.jzmj
  })
  loadHouseOptions()
  dialogVisible.value = true
}

// 删除处理
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除这条成本明细记录吗？', '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await costDetailApi.deleteCostDetail(row.id)
    ElMessage.success('删除成功')
    loadData()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 批量录入处理
const handleBatchAdd = () => {
  Object.assign(batchFormData, {
    fwgn: '',
    totalCost: 0,
    dfcb: 0
  })
  batchHouses.value = []
  batchDialogVisible.value = true
}

// 导出处理
const handleExport = async () => {
  try {
    const params = {
      fycbId: fycbId.value,
      ...searchParams
    }
    
    const response = await costDetailApi.exportExcel(params)
    const blob = new Blob([response.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
    const url = URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `房屋成本明细_${new Date().toISOString().split('T')[0]}.xlsx`
    link.click()
    URL.revokeObjectURL(url)
    
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  }
}

// 导入处理
const handleImport = () => {
  importDialogVisible.value = true
}

// 状态文本
const getStatusText = (zt) => {
  const statusMap = {
    0: '无效',
    1: '活动',
    2: '历史'
  }
  return statusMap[zt] || '未知'
}

// 获取状态标签类型
const getStatusTagType = (status) => {
  const typeMap = {
    0: 'danger',   // 无效 - 红色
    1: 'success',  // 活动 - 绿色
    2: 'info'      // 历史 - 灰色
  }
  return typeMap[status] || 'default'
}

// 获取功能标签类型
const getFunctionTagType = (fwgn) => {
  const typeMap = {
    '办公': 'primary',
    '住宅': 'success',
    '商业': 'warning',
    '车位': 'info',
    '其他': 'default'
  }
  return typeMap[fwgn] || 'default'
}



// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    
    const submitData = {
      fycbId: formData.fycbId,
      fyId: formData.fyId,
      dfcb: formData.dfcb,
      zcb: formData.zcb,
      zt: formData.zt
    }
    
    if (formData.id) {
      await costDetailApi.updateCostDetail(formData.id, submitData)
      ElMessage.success('更新成功')
    } else {
      await costDetailApi.createCostDetail(submitData)
      ElMessage.success('创建成功')
    }
    
    // 更新房屋成本总成本
    await updateCostTotal()
    
    dialogVisible.value = false
    loadData()
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('提交失败')
  }
}

// 批量房源变化
const handleBatchHouseChange = async () => {
  if (!batchFormData.fwgn) {
    batchHouses.value = []
    batchFormData.totalCost = 0
    batchFormData.dfcb = 0
    return
  }
  
  try {
    // 尝试多种方式获取所有房源数据
    let response
    let houses = []
    
    // 方法1：使用大分页
    try {
      response = await houseApi.getHouseList({ 
        size: 2000,
        page: 1
      })
      console.log('方法1 - 大分页API响应:', response)
      
      if (response.data && Array.isArray(response.data)) {
        houses = response.data
      } else if (response.data && response.data.content && Array.isArray(response.data.content)) {
        houses = response.data.content
      } else if (Array.isArray(response)) {
        houses = response
      }
    } catch (error) {
      console.log('方法1失败，尝试方法2:', error)
    }
    
    // 方法2：如果方法1获取的数据太少，尝试获取所有数据
    if (houses.length < 100) {
      try {
        response = await houseApi.getHouseList({ 
          size: 9999,
          page: 1,
          getAll: true
        })
        console.log('方法2 - 获取所有数据API响应:', response)
        
        if (response.data && Array.isArray(response.data)) {
          houses = response.data
        } else if (response.data && response.data.content && Array.isArray(response.data.content)) {
          houses = response.data.content
        } else if (Array.isArray(response)) {
          houses = response
        }
      } catch (error) {
        console.log('方法2也失败:', error)
      }
    }
    
    if (houses.length === 0) {
      console.error('无法获取房源数据')
      ElMessage.error('无法获取房源数据')
      return
    }
    
    console.log('获取到的总房源数量:', houses.length)
    console.log('所有房源的功能类型:', houses.map(h => h.fwgn).filter((v, i, a) => a.indexOf(v) === i))
    console.log('请求的房屋功能类型:', batchFormData.fwgn)
    
    // 临时测试：显示所有房源（不筛选）
    console.log('测试：显示所有房源（前10个）:', houses.slice(0, 10).map(h => ({ id: h.id, mpdz: h.mpdz, fh: h.fh, fwgn: h.fwgn })))
    
    // 筛选指定房屋功能的房源
    batchHouses.value = houses.filter(house => house.fwgn === batchFormData.fwgn)
    console.log('筛选后的房源数量:', batchHouses.value.length)
    
    // 重置成本相关字段
    batchFormData.totalCost = 0
    batchFormData.dfcb = 0
    
    if (batchHouses.value.length > 0) {
      ElMessage.success(`已找到 ${batchHouses.value.length} 套${batchFormData.fwgn}房源，总建筑面积 ${formatNumber(batchTotalArea.value)} m²`)
    } else {
      ElMessage.warning(`未找到${batchFormData.fwgn}类型的房源，请检查房屋功能类型是否正确`)
    }
  } catch (error) {
    console.error('加载房源失败:', error)
    ElMessage.error('加载房源失败，请稍后重试')
  }
}

// 计算批量成本
const calculateBatchCosts = () => {
  if (batchHouses.value.length === 0) {
    batchFormData.dfcb = 0
    return
  }
  
  if (batchFormData.totalCost <= 0) {
    batchFormData.dfcb = 0
    return
  }
  
  batchFormData.dfcb = batchTotalArea.value > 0 ? batchFormData.totalCost / batchTotalArea.value : 0
}

// 批量提交
const handleBatchSubmit = async () => {
  try {
    await batchFormRef.value.validate()
    
    if (batchHouses.value.length === 0) {
      ElMessage.warning('请先选择房屋功能')
      return
    }
    
    if (batchFormData.totalCost <= 0) {
      ElMessage.warning('请输入总成本')
      return
    }
    
    if (batchFormData.dfcb <= 0) {
      ElMessage.warning('单方成本计算错误，请检查输入')
      return
    }
    
    // 确认对话框
    await ElMessageBox.confirm(
      `确定要批量录入 ${batchHouses.value.length} 套${batchFormData.fwgn}房源吗？\n总成本：${formatCurrency(batchFormData.totalCost)}\n单方成本：${formatCurrency(batchFormData.dfcb)}/m²`,
      '确认批量录入',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 先删除现有的明细记录
    const existingDetails = tableData.value.filter(item => 
      item.fycbId === parseInt(fycbId.value)
    )
    
    for (const detail of existingDetails) {
      await costDetailApi.deleteCostDetail(detail.id)
    }
    
    // 批量创建新记录
    const promises = batchHouses.value.map(house => {
      const zcb = (house.jzmj || 0) * batchFormData.dfcb
      return costDetailApi.createCostDetail({
        fycbId: parseInt(fycbId.value),
        fyId: house.id,
        dfcb: batchFormData.dfcb,
        zcb: zcb,
        zt: 1
      })
    })
    
    await Promise.all(promises)
    
    // 更新房屋成本总成本
    await updateCostTotal()
    
    ElMessage.success(`批量录入成功！共录入 ${batchHouses.value.length} 套房源`)
    batchDialogVisible.value = false
    loadData()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量录入失败:', error)
      ElMessage.error('批量录入失败')
    }
  }
}

// 文件变化处理
const handleFileChange = (file) => {
  selectedFile.value = file.raw
}

// 上传前验证
const beforeUpload = (file) => {
  const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
                  file.type === 'application/vnd.ms-excel'
  const isLt10M = file.size / 1024 / 1024 < 10

  if (!isExcel) {
    ElMessage.error('只能上传 Excel 文件!')
    return false
  }
  if (!isLt10M) {
    ElMessage.error('文件大小不能超过 10MB!')
    return false
  }
  return false // 阻止自动上传
}

// 导入提交
const handleImportSubmit = async () => {
  if (!selectedFile.value) {
    ElMessage.warning('请选择要导入的文件')
    return
  }
  
  try {
    await costDetailApi.importExcel(selectedFile.value)
    ElMessage.success('导入成功')
    importDialogVisible.value = false
    loadData()
  } catch (error) {
    console.error('导入失败:', error)
    ElMessage.error('导入失败')
  }
}

// 加载房源选项
const loadHouseOptions = async () => {
  try {
    // 尝试多种方式获取所有房源数据
    let response
    let houses = []
    
    // 方法1：使用大分页
    try {
      response = await houseApi.getHouseList({ 
        size: 2000,
        page: 1
      })
      console.log('房源选项 - 方法1API响应:', response)
      
      if (response.data && Array.isArray(response.data)) {
        houses = response.data
      } else if (response.data && response.data.content && Array.isArray(response.data.content)) {
        houses = response.data.content
      } else if (Array.isArray(response)) {
        houses = response
      }
    } catch (error) {
      console.log('房源选项 - 方法1失败，尝试方法2:', error)
    }
    
    // 方法2：如果方法1获取的数据太少，尝试获取所有数据
    if (houses.length < 100) {
      try {
        response = await houseApi.getHouseList({ 
          size: 9999,
          page: 1,
          getAll: true
        })
        console.log('房源选项 - 方法2API响应:', response)
        
        if (response.data && Array.isArray(response.data)) {
          houses = response.data
        } else if (response.data && response.data.content && Array.isArray(response.data.content)) {
          houses = response.data.content
        } else if (Array.isArray(response)) {
          houses = response
        }
      } catch (error) {
        console.log('房源选项 - 方法2也失败:', error)
      }
    }
    
    if (houses.length === 0) {
      console.error('无法获取房源选项数据')
      return
    }
    
    console.log('房源选项 - 获取到的总房源数量:', houses.length)
    houseOptions.value = houses
  } catch (error) {
    console.error('加载房源失败:', error)
  }
}

// 房源变化处理
const handleHouseChange = () => {
  const selectedHouse = houseOptions.value.find(h => h.id === formData.fyId)
  if (selectedHouse) {
    formData.jzmj = selectedHouse.jzmj
    calculateTotalCost()
  }
}

// 计算总成本
const calculateTotalCost = () => {
  formData.zcb = (formData.jzmj || 0) * (formData.dfcb || 0)
}

// 更新房屋成本总成本
const updateCostTotal = async () => {
  try {
    const details = tableData.value.filter(item => item.fycbId === parseInt(fycbId.value))
    const totalCost = details.reduce((sum, item) => sum + (item.zcb || 0), 0)
    
    await costApi.updateCost(parseInt(fycbId.value), { zcb: totalCost })
  } catch (error) {
    console.error('更新房屋成本失败:', error)
  }
}

// 页面初始化
onMounted(() => {
  console.log('房屋成本明细页面已加载，fycbId:', fycbId.value)
  if (fycbId.value) {
    loadData()
  }
})
</script>

<style scoped>
@import '@/styles/page.css';

/* 搜索筛选样式 */
.cost-detail-search,
.cost-detail-room-search,
.cost-detail-function-select,
.cost-detail-status-select {
  display: flex;
  align-items: center;
  gap: 8px;
}

.label {
  font-size: 14px;
  color: var(--text-secondary, #606266);
  white-space: nowrap;
}

/* 表格容器样式 */
.table-container {
  flex: 1;
  width: 100%;
  min-height: 0;
  max-width: 100%;
  background: white;
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  border: 1px solid rgba(0, 0, 0, 0.05);
  padding: 20px;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  box-sizing: border-box;
}

.table-container .base-table-container {
  flex: 1;
  width: 100%;
  min-height: 0;
  max-width: 100%;
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
}

/* 表格样式与主题协调 */
:deep(.el-table) {
  width: 100% !important;
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-table__header) {
  background: var(--primary-color, #409eff);
}

:deep(.el-table__header th) {
  background: var(--primary-color, #409eff) !important;
  color: white !important;
  font-weight: 600;
  padding: 5px !important;
}

:deep(.el-table__body td) {
  padding: 5px !important;
  border-bottom: 1px solid var(--border-light, #ebeef5);
  font-weight: normal;
  color: #303133;
}

:deep(.el-table--striped .el-table__body tr.el-table__row--striped td) {
  background: var(--table-stripe-background, #fafafa);
}

:deep(.el-table__body tr:hover) {
  background-color: rgba(64, 158, 255, 0.1);
}

/* 分页器样式 */
.pagination-wrapper {
  padding: 20px;
  background: white;
  display: flex;
  justify-content: center;
  align-items: center;
  border-top: 1px solid #e4e7ed;
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.05);
  margin-top: 10px;
  border-radius: 0 0 8px 8px;
}

.pagination-wrapper .el-pagination {
  --el-pagination-bg-color: transparent;
  --el-pagination-text-color: #606266;
  --el-pagination-border-radius: 4px;
  --el-pagination-button-color: #606266;
  --el-pagination-button-bg-color: #ffffff;
  --el-pagination-button-disabled-color: #c0c4cc;
  --el-pagination-button-disabled-bg-color: #ffffff;
  --el-pagination-hover-color: #409eff;
  --el-pagination-hover-bg-color: #ecf5ff;
}

.pagination-wrapper .el-pagination .el-pager li {
  border-radius: 4px;
  margin: 0 2px;
  transition: all 0.3s ease;
}

.pagination-wrapper .el-pagination .el-pager li.is-active {
  background-color: #409eff;
  color: white;
  font-weight: 600;
}

.pagination-wrapper .el-pagination .el-pager li:hover {
  background-color: #ecf5ff;
  color: #409eff;
}

.pagination-wrapper .el-pagination .btn-prev,
.pagination-wrapper .el-pagination .btn-next {
  border-radius: 4px;
  margin: 0 4px;
  transition: all 0.3s ease;
}

.pagination-wrapper .el-pagination .btn-prev:hover,
.pagination-wrapper .el-pagination .btn-next:hover {
  background-color: #ecf5ff;
  color: #409eff;
}

.pagination-wrapper .el-pagination .el-pagination__sizes {
  margin-right: 15px;
}

.pagination-wrapper .el-pagination .el-pagination__jump {
  margin-left: 15px;
}

/* 表格内容样式 */
.address-text {
  font-weight: normal;
  color: #303133;
}

.room-text {
  font-weight: normal;
  color: #303133;
}

.area-text {
  font-weight: normal;
  color: #303133;
}

.cost-text {
  font-weight: 600;
  color: #e6a23c;
  font-size: 14px;
}

.total-cost-text {
  font-weight: 600;
  color: #f56c6c;
  font-size: 14px;
}

.version-text {
  font-weight: normal;
  color: #606266;
  font-size: 12px;
}

.action-buttons {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

:deep(.el-tag) {
  border-radius: 4px;
}

:deep(.el-dialog__body) {
  padding: 20px;
}

:deep(.el-form-item) {
  margin-bottom: 20px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .table-container {
    padding: 8px;
  }
  
  .pagination-wrapper {
    padding: 10px;
  }
  
  .pagination-wrapper .el-pagination {
    font-size: 12px;
  }
  
  .pagination-wrapper .el-pagination .el-pagination__sizes {
    margin-right: 10px;
  }
  
  .pagination-wrapper .el-pagination .el-pagination__jump {
    margin-left: 10px;
  }
}

@media (max-width: 480px) {
  .pagination-wrapper {
    flex-direction: column;
    gap: 10px;
  }
  
  .pagination-wrapper .el-pagination {
    justify-content: center;
  }
}
</style> 